/*
 * Copyright (c) 2016,重庆阿莫比科技有限公司,All Rights Reserved.
 */
package com.wowocai.btchina.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.wowocai.btchina.entity.AmazonProductAdEntity;
import com.wowocai.btchina.entity.PagerEntity;
import com.wowocai.btchina.entity.WebTorrentEntity;
import com.wowocai.btchina.service.AmazonAdsService;
import com.wowocai.btchina.service.SearchEngineService;

/**
 * 搜索相关页面<br/>
 * Date: 2016年12月30日 上午11:41:26 <br/>
 * 
 * @Author 刘建成
 * @Version
 */
@Controller
public class SearchController extends BaseController {

    private final static Logger logger = LoggerFactory.getLogger(SearchController.class);

    @Autowired
    private SearchEngineService searchEngineService;

    @Autowired
    private AmazonAdsService amazonAdsService;

    /**
     * Creates a new instance of IndexController.
     */
    public SearchController() {

    }

    @RequestMapping(value = "/{lang}/search.html", method = RequestMethod.GET)
    public String i18nSearch(ModelMap model, @PathVariable(required = true) String lang,
            @RequestParam(required = false) String kw, HttpServletRequest request) {
        return search(model, kw, request);
    }

    @RequestMapping(value = "/search.html", method = RequestMethod.GET)
    public String search(ModelMap model, @RequestParam(required = false) String kw, HttpServletRequest request) {
        //StopWatch sw = new StopWatch();
        long start = System.currentTimeMillis();
        if (StringUtils.isBlank(kw)) {
            return "redirect:/index.html";
        }
        //sw.start("搜索");
        PagerEntity<WebTorrentEntity> page = searchEngineService.search(kw, null, 1, 10);
        //sw.stop();
        model.put("page", page);
        model.put("sort", 1);
        try {
            model.put("q", URLDecoder.decode(kw, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            model.put("q", kw);
        }
        //sw.start("国家编码");
        this.getClientAdCountry(request);
        //sw.stop();
        //sw.start("广告");
        List<AmazonProductAdEntity> ads = amazonAdsService.getAmazonAds(AmazonAdsService.AD_KEY_COMPUTER);
        model.put("ads", ads);
        //sw.stop();

        long end = System.currentTimeMillis();
        logger.info("查询用时{}MS", (end - start));
        //logger.info(sw.prettyPrint());
        return "list";
    }

    @RequestMapping(value = "/{lang}/search/{name}_{sort}_{pageNo}.html", method = RequestMethod.GET)
    public String i18nSearch(ModelMap model, @PathVariable String name, @PathVariable(required = true) String lang,
            @PathVariable(required = false) Integer sort, @PathVariable Integer pageNo, HttpServletRequest request) {
        return search(model, name, sort, pageNo, request);
    }

    /**
     * 
     * <br/>
     * 
     * @author 刘建成
     * @param model
     * @param name
     * @param sort
     * @param pageNo
     * @param request
     * @return
     */
    @RequestMapping(value = "/search/{name}_{sort}_{pageNo}.html", method = RequestMethod.GET)
    public String search(ModelMap model, @PathVariable String name, @PathVariable(required = false) Integer sort,
            @PathVariable Integer pageNo, HttpServletRequest request) {
        long start = System.currentTimeMillis();
        if (StringUtils.isBlank(name)) {
            return "redirect:/index.html";
        }
        this.getClientAdCountry(request);
        int sort_ = sort == null ? 1 : sort;
        String srt = null;
        // 默认为相关性排序
        switch (sort_) {
            case 2:
                srt = "createtime";
                break;
            case 3:
                srt = "vcount";
                break;
            case 4:
                srt = "size";
                break;
            default:
                // srt = "_score";
                break;
        }

        if (pageNo == null) {
            pageNo = 1;
        }
        PagerEntity<WebTorrentEntity> page = searchEngineService.search(name, srt, pageNo, 10);
        model.put("page", page);
        model.put("sort", sort_);
        try {
            model.put("q", URLDecoder.decode(name, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            model.put("q", name);
        }
        List<AmazonProductAdEntity> ads = amazonAdsService.getAmazonAds(AmazonAdsService.AD_KEY_COMPUTER);
        model.put("ads", ads);
        long end = System.currentTimeMillis();
        logger.info("查询用时{}MS", (end - start));
        return "list";
    }

    @RequestMapping(value = { "/detail/{infohash}/*", "/detail/{infohash}" }, method = RequestMethod.GET)
    public String detail(ModelMap model, @PathVariable(required = true) String infohash, HttpServletResponse response,
            HttpServletRequest request) {
        long start = System.currentTimeMillis();
        if (StringUtils.isBlank(infohash)) {
            return "redirect:/index.html";
        }
        WebTorrentEntity bean = searchEngineService.findTorrentByInfohash(infohash);
        if (bean == null) {
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return "error/404";
        }
        this.getClientAdCountry(request);
        model.put("q", "");
        model.put("bean", bean);
        List<AmazonProductAdEntity> ads = null;
        if (bean.isVideo) {
            ads = amazonAdsService.getAmazonAds(AmazonAdsService.AD_KEY_MOVIE);
        } else {
            ads = amazonAdsService.getAmazonAds(AmazonAdsService.AD_KEY_BOOK);
        }
        model.put("ads", ads);
        long end = System.currentTimeMillis();
        logger.info("详细页面用时{}MS", (end - start));
        return "detail";
    }

    @RequestMapping(value = { "/{lang}/detail/{infohash}/*", "/{lang}/detail/{infohash}" }, method = RequestMethod.GET)
    public String i18nDetail(ModelMap model, @PathVariable(required = true) String infohash,
            @PathVariable(required = true) String lang, HttpServletResponse response, HttpServletRequest request) {
        return detail(model, infohash, response, request);
    }

}
